unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

const
  A = 5;
  N = 50;

type
  TForm1 = class(TForm)
    Image1: TImage;
    ScrollBar1: TScrollBar;
    Timer1: TTimer;
    procedure Timer1Timer(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Draw (b: integer);
    private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  arr: array [0..N] of integer;
  Step, runNumber, c: integer;
  flag: boolean;

implementation

{$R *.dfm}

procedure TForm1.Timer1Timer(Sender: TObject);
var t, i: integer;
begin
  Timer1.Interval:= ScrollBar1.Position;
  if (arr[step]>arr[step+1]) then
  begin
    t:= arr[step];
    arr[step]:= arr[step+1];
    arr[step+1]:= t;
    flag:= false;
  end;
  Draw(step);
  inc(step);
  if (step=N-2-runNumber) then
  begin
    step:= 0;
    inc(runNumber);
    if (runNumber=N-2) or (flag) then
      Timer1.Enabled:= false;
    flag:= true;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var i: integer;
begin
  randomize;
  for i:=0 to N-2 do
    arr[i]:= random(100);
  Step:= 0;
  runNumber:= 0;
  Draw(-1);
  c:= Image1.Height div 100;
  flag:= true;
end;

procedure TForm1.Draw(b: integer);
var i: integer;
begin
  Image1.Canvas.Rectangle(Image1.ClientRect);
  for i := 0 to N-1 do
  begin
    Image1.Canvas.Pen.Color:= clBlack;
    Image1.Canvas.Brush.Color:= clWhite;
    if ((i=b) and (i+1=b+1)) or ((i=b+1) and (i-1=b)) then
    begin
      Image1.Canvas.Pen.Color:= clRed;
      Image1.Canvas.Brush.Color:= clRed;
    end;
    Image1.Canvas.Rectangle(a*i, 0, a*(i+1), c*arr[i]);
  end;
end;

end.

